package com.rustic.server.controller.api;

import cn.xy.base.server.service.UploadService;
import cn.xy.commons.annotation.ApiAuth;
import cn.xy.commons.constant.Consts;
import cn.xy.commons.core.Result;
import com.rustic.server.web.WebContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

/**
 * 上传接口
 *
 * @author JianZheng
 */

@Slf4j
@RestController
@RequestMapping("/api/upload")
@Api(tags = {"上传接口"})
@ApiAuth(ignore = true)
public class UploadController {

    @Autowired
    @Qualifier("uploadService")
    private UploadService uploadService;

    @PostMapping
    @ApiOperation(value = "上传接口")
    public Result<HashMap<String, Object>> uploadFile(@RequestParam MultipartFile file) {
        int userId = WebContext.getUserId();
        if (userId == 0) {
            return Result.error(Consts.NO_LOGIN_CODE, "登录信息已失效，请重新登录");
        }
        if (file == null || file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }
        String fileUrl = uploadService.upload(file);
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("url", fileUrl);
        return Result.data(map);
    }

}

